/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.testing;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;


import lime2.Location;
import lime2.TupleID;

import sagroup.dracots.DracoConstants;
import sagroup.dracots.DracoTS;
import sagroup.dracots.FlatShareTuple;
import sagroup.dracots.TupleType;

/**
 * @author Xing Jiankuan
 *
 */
public class OutAgent extends AbstractAgent {

	// This is the average value for exponential distribution of out frequency
	private long meaninternal;
	// This is the params for Gaussian distribution for size of tuple 
	private long mu, sigma;
	// Type of tuple
	private TupleType type;
	
	private boolean timesup = false;
	private int opCount = 0;
	
	private long usedTotalTime = 0L; 
	
	private DracoTS dts;
	
	private Logger LOG = Logger.getLogger(this.getClass().getName());
	
	int icount = 0;
	
	/**
	 * 
	 */
	public OutAgent(HashMap<String, String> params,
			Long[][] array)/*tring agentName, String typeName, String meaninternal, 
			String mu, String sigma) */{
		super(params.get("agentname"),Long.valueOf(params.get("meaninternal")),
				array);
		try {
			this.type = new TupleType(params.get("typename"));
			this.meaninternal = Long.valueOf(params.get("meaninternal"));
			this.mu = Long.valueOf(params.get("mu"));
			this.sigma = Long.valueOf(params.get("sigma"));
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}

		if (this.meaninternal < 0 || this.mu < 0 || this.sigma < 0) {
			throw new IllegalArgumentException("Parameters are illegal.");
		}
		initialize();
	}
	
	private void initialize() {
		Timer timer = new Timer();
		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				timesup = true;
				
			}
		};
		timer.schedule(tt, AgentUtil.expTime);
		Timer timer1 = new Timer();
		TimerTask tt1 = new TimerTask() {
			Runtime r = Runtime.getRuntime();
			@Override
			public void run() {
				if(!timesup||icount==0){
			     	LOG.info("Out Count " + agentName + " " + type + ":" + opCount);
					LOG.info(agentName + " -> Total Memory: " + r.totalMemory()
							+ "Used memory: " + (r.totalMemory() - r.freeMemory()));
				}
				if(timesup)
					icount = 1;
			}
		};
		
		timer1.schedule(tt1, DracoConstants.ADAPTATION_PERIOD,DracoConstants.ADAPTATION_PERIOD);
		Timer timer2 = new Timer();
		TimerTask tt2 = new TimerTask() {
			@Override
			public void run() {
				ListTuple lt;
				HashSet<TupleID> set = new HashSet<TupleID>();
				synchronized(hashSet)
				{
				    set.addAll(hashSet);
					hashSet.clear();
				}
				lt= ListTuple.createLocalList(type, set);
				dts.outgToMulti(new ListTuple[]{lt}, 
                       dts.getAllEngagedLocations());
				dts.out(lt);
			}
		};
		
		timer2.schedule(tt2, DracoConstants.ADAPTATION_PERIOD/3,DracoConstants.ADAPTATION_PERIOD/3);
		
		dts = DracoTS.get("testing");
		
	}
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	
	private RandomData randomData = new RandomDataImpl();
	private RandomData randomSize = new RandomDataImpl();
	private HashSet<TupleID> hashSet = new HashSet();
	private Random random = new Random();
	
	@Override
	public void run() {
		super.run();
		
		sleepWait(AgentUtil.sleepTime);
		
		System.out.println(this.agentName+" Start working....");
		while (!this.timesup) {
			
			FlatShareTuple tempTuple = createRandomTuple();
			synchronized(hashSet)
			{
				hashSet.add(tempTuple.getVID());
			}
			long begin = System.nanoTime();
			dts.out(tempTuple);
			long temp = System.nanoTime() - begin; 
			usedTotalTime += temp;
			if (tempTuple != null) {
				LOG.info(String.format("%s has out tuple (vid%s), replica:%b version:%d Optime:%g", 
						agentName, 
						tempTuple.getVID(), 
						tempTuple.isReplica(), 
						tempTuple.getVer(),
						temp / 1000000000.0));
			}
			//System.out.println("Number: " + i + "\tLength: " + aString.length());
			opCount++;
			rest(temp/1000000);
		
		};
		double timePerOp = usedTotalTime / 1000000000.0 / opCount;
		Runtime r = Runtime.getRuntime();
		String msg = "$$$$" + this.getAgentName() + "::optime:" + timePerOp + ";mem:" + (r.totalMemory() - r.freeMemory()) + ";$$$";
		LOG.info(msg);
		LOG.info(agentName + " has finished");
		AgentServer.done();
	}

	private FlatShareTuple createRandomTuple()
	{
		double tupleSize = randomSize.nextGaussian(mu, sigma);
		byte []data = new byte[(int)tupleSize];
		if(data == null){
			System.out.println("Allocate failed!");
			System.exit(0);
		} else{
			random.nextBytes(data);
		}
		
		FlatShareTuple t = makeNewTuple(type, data);
		return t;
	}
	

	@Override
	public Location getTargetLocation() {
		
		return Location.HERE;
	}
	@Override
	public TupleType getType() {
		
		return type;
	}
	@Override
	public void updateList(ListTuple lt) {
		return;
		
	}
}
